package com.stand.hardcode.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.stand.hardcode.entity.StandUser;
import com.stand.hardcode.exception.UsernameTakenException;
import com.stand.hardcode.manager.UserManager;
import com.stand.hardcode.util.RequestAttributes;
//login
public class LogInServlet extends HttpServlet{
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	
		UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    
	    if (user != null) {
	    	if(UserManager.ExistsUser(user.getEmail())){
	    		 StandUser currentuser = UserManager.RetrieveUser(KeyFactory.createKey(StandUser.class.getSimpleName(), user.getEmail()));
	    		 if(!currentuser.isActive()){
	    			 try {
						req.getRequestDispatcher("deactivated.jsp").forward(req, resp);
					} catch (ServletException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    		 }else{
		    		req.getSession().setAttribute(RequestAttributes.CURRENT_USER, currentuser);
		            resp.sendRedirect("/home");
		    	 }
	    	}else{
	    		try {
					req.getRequestDispatcher("notregistered.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
           
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
		
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	
	}
}
